package breeze.lepei.der.utils;
import java.io.Writer;
import java.io.StringWriter;
import java.io.PrintWriter;
import android.content.Context;
import java.io.IOException;

public class AppExceptionCacher implements Thread.UncaughtExceptionHandler {
	
	private static AppExceptionCacher exceptionCahcher;
	private static Context mContext;

	/**
	*@author BREEZE
	*@description 获取类实例
	*@return 本类
	*@param Context
	*/
	public static AppExceptionCacher getInstance(Context context){
		if(exceptionCahcher==null){
			exceptionCahcher=new AppExceptionCacher(context);
		}
		return exceptionCahcher;
	}
	
	public AppExceptionCacher(Context context){
		this.mContext=context;
	}
	
	/**
	*@author BREEZE
	*@description 全局错误日志抓取
	*/
	@Override
	public void uncaughtException(Thread p1, Throwable p2) {
		Writer writer=new StringWriter();
		PrintWriter pw=new PrintWriter(writer);
		p2.printStackTrace(pw);
		Throwable throwable=p2.getCause();
		while(throwable!=null){
			throwable.printStackTrace(pw);
			throwable=throwable.getCause();
		}
		String exception=writer.toString();
		//写出至本地cache目录
		if(mContext!=null){
			try {
				AppTools.writeDataToFile(exception, AppTools.getAppExceptionFilePath(mContext));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
